package com.ruoyi.framework.datasource.aspectj;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.datasource.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;


@Aspect
@Component
@Slf4j
@Order(1)
public class DynamicDataSourceAspect {



    @Autowired
    private RedisCache redisCache;


    @Around("execution(* com.nxhz.dao.*.mapper..*(..))")
    public Object around(ProceedingJoinPoint point) throws Throwable {


        //String className =((ReflectiveMethodInvocation) ((MethodInvocationProceedingJoinPoint) point).signature).method.clazz.name;

        Signature signature = point.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method targetMethod = methodSignature.getMethod();


        Object[] mapperInterfaces = point.getTarget().getClass().getInterfaces();
        String mapperInterfaceName = "";
        if (mapperInterfaces.length > 0) {
            mapperInterfaceName = point.getTarget().getClass().getInterfaces()[0].getName();
        }


        System.out.println();
        String className = targetMethod.getDeclaringClass().getName();

        //log.info("classname:" + targetMethod.getDeclaringClass().getName());
        //log.info("superclass:" + targetMethod.getDeclaringClass().getSuperclass().getName());
        //log.info("isinterface:" + targetMethod.getDeclaringClass().isInterface());
        //log.info("target:" + point.getTarget().getClass().getName());
        //log.info("proxy:" + point.getThis().getClass().getName());
        //log.info("method:" + targetMethod.getName());

        if (mapperInterfaceName.contains("com.nxhz.dao")) {
            className = mapperInterfaceName;
        }


        try {


            String pageName=className.substring(0,className.indexOf(".mapper"));
            String pageKey = Constants.DATA_SOURCE_KEY + pageName;



            String source_code = redisCache.getCacheObject(pageKey);
            if (StringUtils.isNotEmpty(source_code)) {
                DynamicDataSourceContextHolder.setDataSourceType(source_code);
            }

            return point.proceed();

        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }
}
